import sys
import traceback
import threading
import time
import nacos

from PySide6.QtWidgets import QApplication
from PySide6.QtGui import QAction
from PySide6.QtUiTools import QUiLoader
from PySide6.QtWidgets import QTextEdit, QComboBox, QCheckBox, QListWidget, QPushButton
from PySide6.QtWidgets import QAbstractItemView, QMenu, QTabWidget
from test_tools.view.excel_tools_message_view import ExcelToolsMessageView
from qt_material import apply_stylesheet
from test_tools.script.thread_worker import ThreadWorker_Signal

from test_tools.script.tool_box import *
from test_tools.script import debug_log
from test_tools.script.my_print import MyPrint

my_print = MyPrint()
log = debug_log.log


# def get_root_path() -> (bool, str):
#     """获取项目根目录。
#     Returns:
#         bool: 返回是否为测试模式
#         str: 返回项目根目录。
#     """
#     is_test = False
#     working_dir = os.getcwd()
#     if "data" not in working_dir:
#         log(f"程序运行目录异常，请检查目录路劲是否正确： {working_dir}")
#     else:
#         if "test_tools" in working_dir:
#             log("----------------test路径----------------")
#             working_dir = working_dir[:-11].strip()
#             is_test = True
#             if os.path.exists(working_dir) and os.path.isdir(working_dir):
#                 os.chdir(working_dir)
#                 print(f"新工作目录: {os.getcwd()}")
#         else:
#             log("----------------data路径----------------")
#     log(f"根目录：{working_dir}")
#     return is_test, working_dir

def test_re_for_list():
    log("----------------正则匹配测试----------------")
    test_list = [
        r"D:\hope_city_game\dev_2.0\data",
        r"D:\hope_city_game\dev_2.0",
        r"D:\hope_city_game\dev_2.0\data\test_tools",
        r"D:\\hope_city_game\\dev_2.0\\data\\test_tools",
        r"D:/hope_city_game/dev_2.0/data/test_tools",
        r"D:\\hope_city_game/dev_2.0/data/test_tools",
        r"D:\\hope_city_game/dev_2.0/abcd/data/test_tools",
        r"D:\\hope_city_game/dev_2.0/data/data/test_tools"
    ]
    target_dir = "data"
    pattern = rf"^[A-Za-z]:[\\\\/]+(?:[^\\\\/]+[\\\\/]+)*{target_dir}"
    for path in test_list:
        match = re.match(pattern, path, re.I)
        if match:
            log(f"匹配成功：{match.group()}")
        else:
            log(f"匹配失败: {path}")
    log("----------------正则匹配测试----------------")


def test_re(test_paths):
    log("----------------正则匹配测试----------------")
    target_dir = "data"
    pattern = rf"^[A-Za-z]:[\\\\/]+(?:[^\\\\/]+[\\\\/]+)*{target_dir}"
    match = re.match(pattern, test_paths, re.I)
    if match:
        _path = match.group()
        log(f"匹配成功：{_path}")
        log("----------------正则匹配测试----------------")
        return _path
    else:
        log("匹配失败")
        log("----------------正则匹配测试----------------")
        return None


def get_root_path() -> str:
    """获取项目根目录。
    Returns:
        bool: 返回是否为测试模式
        str: 返回项目根目录。
    """
    # test_re_for_list()
    working_dir = os.getcwd()
    _path = test_re(working_dir)
    if _path is None:
        log(f"程序运行目录异常，请检查程序所在目录是否正确： {working_dir}")
    else:
        if working_dir != _path:
            log("----------------test路径----------------")
            log(f"原工作目录：{working_dir}")
            if os.path.exists(_path) and os.path.isdir(_path):
                os.chdir(_path)
                log(f"新工作目录: {os.getcwd()}")
            working_dir = _path
        else:
            log("----------------data路径----------------")
    log(f"根目录：{working_dir}")
    return working_dir


def prin_error():
    """获取错误信息堆栈，并且使用高亮颜色输出"""
    error_details = traceback.format_exc()
    log(error_details)
    try:
        my_print.print(f"异常：{error_details}", 2)
    except Exception as e:
        log(e)
        raise e


class PathTool:
    def __init__(self):
        # 基础路径
        self.root_path = None
        # self.excel_tools_view_ui = "excel_tools_view.ui"
        self.excel_tools_view_ui = "excel_tools_view.ui"
        self.error_log_view_ui = "error_log_view.ui"
        self.excel_tool_config_json = "excel_tool_config.json"
        self.nacos_requests_config = "nacos_requests_config_.json"
        self.Style_qss = "Style.qss"
        # self.Style_qss = "Style_0.qss"
        # self.Style_qss = "material.qss"
        self.time_txt = "time.txt"
        self._proton_py = "_proton.py"
        self.server_config_txt = "server_config.txt"
        self.config_server = "config_server"
        self.config_client = "config_client"
        self.server_list_json = "server_list.json"
        self.test_tools = "test_tools/"
        self.resources = f"{self.test_tools}resources/"
        self.script = f"{self.test_tools}script/"
        self.view = f"{self.test_tools}view/"
        # resources目录拼接
        self.excel_tools_config_path = f"{self.resources}{self.excel_tool_config_json}"  # 主窗口配置文件
        # self.time_path = f"{self.resources}{self.time_txt}"  # 更新服务器配置列表时间戳
        self.server_list_path = f"{self.resources}{self.server_list_json}"  # nacos配置文件
        self.server_config_path = f"{self.resources}{self.server_config_txt}"  # 服务器配置列表
        self.nacos_requests_config_path = f"{self.resources}{self.nacos_requests_config}"  # nacos发送请求配置文件
        # script目录拼接
        self.proton_path = f"{self.script}{self._proton_py}"  # 导表用到的python文件
        # view目录拼接
        self.excel_tools_view_ui_path = f"{self.view}{self.excel_tools_view_ui}"  # 主窗口UI文件
        self.error_log_view_ui_path = f"{self.view}{self.error_log_view_ui}"  # 主窗口UI文件
        self.style_qss_path = f"{self.view}{self.Style_qss}"  # 主窗口样式文件
        # data目录
        self.dirServer = f"{self.config_server}"  # 服务器导表目录
        self.dirClient = f"{self.config_client}"  # 客户端导表目录
        self.all_excel = "excel/"  # excel文件夹
        self.export_excel = "export_excel/"  # export_excel文件夹
        self.excel_path = None  # excel文件夹完整路径
        self.export_excel_path = None  # export_excel文件夹完整路径
        self.hope_city_path = f"{self.export_excel}/hope_city2"  # 热更压缩文件夹完整路径
        self.init_path()
        # self.print_all_path()

    def init_path(self):
        self.root_path = get_root_path()
        #  设置各个文件路径
        self.excel_tools_config_path = join_path(self.root_path, self.excel_tools_config_path)
        # self.time_path = join(self.root_path, self.time_path)
        self.server_list_path = join_path(self.root_path, self.server_list_path)
        self.proton_path = join_path(self.root_path, self.proton_path)
        self.excel_tools_view_ui_path = join_path(self.root_path, self.excel_tools_view_ui_path)
        self.error_log_view_ui_path = join_path(self.root_path, self.error_log_view_ui_path)
        self.style_qss_path = join_path(self.root_path, self.style_qss_path)
        self.server_config_path = join_path(self.root_path, self.server_config_path)
        self.nacos_requests_config_path = join_path(self.root_path, self.nacos_requests_config_path)
        self.dirServer = join_path(self.root_path, self.dirServer)
        self.dirClient = join_path(self.root_path, self.dirClient)
        self.excel_path = join_path(self.root_path, self.all_excel)
        self.export_excel_path = join_path(self.root_path, self.export_excel)
        self.hope_city_path = join_path(self.root_path, self.hope_city_path)

    def print_all_path(self):
        log(">>>>>>>>>>>>>>>>>>>>>>>>PathTool目录输出【开始】<<<<<<<<<<<<<<<<<<<<<<<<")
        log(f"****** root_path ******")
        log(self.root_path)
        log(">>>>>>resources目录<<<<<<")
        log(self.excel_tools_config_path)
        # log(self.time_path)
        log(self.server_list_path)
        log(self.server_config_path)
        log(self.nacos_requests_config_path)
        log(">>>>>>script目录<<<<<<")
        log(self.proton_path)
        log(">>>>>>view目录<<<<<<")
        log(self.excel_tools_view_ui_path)
        log(self.error_log_view_ui_path)
        log(self.style_qss_path)
        log(">>>>>>data目录<<<<<<")
        log(self.dirServer)
        log(self.dirClient)
        log(self.excel_path)
        log(self.hope_city_path)
        log(self.export_excel_path)
        log(">>>>>>>>>>>>>>>>>>>>>>>>PathTool目录输出【完毕】<<<<<<<<<<<<<<<<<<<<<<<<")


def get_pathTool(_class=""):
    log(f"{_class} >>> get_pathTool")
    return PathTool()


def print_all_path():
    log(">>>>>>>>>>>>>>>>>>>>>>>>print_path<<<<<<<<<<<<<<<<<<<<<<<<")
    log(f"****** root_path ******")
    log(root_path)
    log(">>>>>>resources目录<<<<<<")
    log(excel_tools_config_path)
    # log(time_path)
    log(server_list_path)
    log(">>>>>>script目录<<<<<<")
    log(proton_path)
    log(">>>>>>view目录<<<<<<")
    log(excel_tools_view_ui_path)
    log(error_log_view_ui_path)
    log(style_qss_path)
    log(server_config_path)
    log(nacos_requests_config_path)
    log(">>>>>>data目录<<<<<<")
    log(dirServer)
    log(dirClient)
    log(excel_path)
    log(hope_city_path)
    log(export_excel_path)
    log(">>>>>>>>>>>>>>>>>>>>>>>>print_path<<<<<<<<<<<<<<<<<<<<<<<<")


path_tool = get_pathTool(os.path.basename(__file__))

root_path = path_tool.root_path
# resources目录
excel_tools_config_path = path_tool.excel_tools_config_path
# time_path = path_tool.time_path
server_list_path = path_tool.server_list_path
server_config_path = path_tool.server_config_path
nacos_requests_config_path = path_tool.nacos_requests_config_path
# script目录
proton_path = path_tool.proton_path
# view目录
excel_tools_view_ui_path = path_tool.excel_tools_view_ui_path
error_log_view_ui_path = path_tool.error_log_view_ui_path
style_qss_path = path_tool.style_qss_path
# data目录
dirServer = path_tool.dirServer
dirClient = path_tool.dirClient
all_excel = path_tool.all_excel
export_excel = path_tool.export_excel
excel_path = path_tool.excel_path
hope_city_path = path_tool.hope_city_path
export_excel_path = path_tool.export_excel_path

print_all_path()
